<template>
  <div class="app-container">
    <el-form label-width="120px">
      <el-form-item label="信息描述">
        <el-tag type="info">请下载模板，并根据描述填充Excel，然后完成上传</el-tag>
        <el-tag>
          <i class="el-icon-download"/>
          <a :href="defaultExcelTemplate">点击下载模版</a>
        </el-tag>

      </el-form-item>

      <el-form-item label="选择Excel">
        <el-upload
          ref="upload"
          :auto-upload="false"
          :on-exceed="fileUploadExceed"
          :on-success="fileUploadSuccess"
          :on-error="fileUploadError"
          :limit="1"
          :action="BASE_API+'/admin/edu/subject/import'"
          name="file"
          accept="application/vnd.ms-excel">
          <el-button
            slot="trigger"
            size="small"
            type="primary">选取文件</el-button>
          <el-button
            :disabled="importBtnDisabled"
            style="margin-left: 10px;"
            size="small"
            type="success"
            @click="submitUpload()">导入</el-button>
        </el-upload>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      BASE_API: process.env.BASE_API,
      defaultExcelTemplate: process.env.OSS_PATH + '/excel/课程分类列表.xls', // 默认Excel模板
      importBtnDisabled: false // 导入按钮是否禁用
    }
  },

  methods: {
    submitUpload() {
      console.log('文件上传')
      this.importBtnDisabled = true
      // 获取upload组件
      this.$refs.upload.submit() // 手动上传
    },

    // 选取的文件超出limit属性限制的数量，触发此方法
    fileUploadExceed() {
      this.$message.warning('只能选择一个文件')
    },

    fileUploadSuccess(response) {
      this.importBtnDisabled = false
      if (response.success) {
        this.$message.success(response.message)
      } else {
        this.$message.error('批量导入失败！')
      }
      // 清空文件列表
      this.$refs.upload.clearFiles()
    },

    fileUploadError() {
      this.importBtnDisabled = false
      this.$message.error('批量导入失败！')
      this.$refs.upload.clearFiles()
    }
  }
}
</script>
